<!-- 角色编辑弹窗 -->
<template>
  <div>
    <el-drawer :visible="drawerEditBoolen"
               size="50%"
               :before-close="handleClose"
               ref="drawer">
      <template v-slot:title>
        <span class="hLabel">{{ isUpdate ? '修改套餐卡' : '添加套餐卡' }}</span>
      </template>
      <div class="ele-body">
        <el-card shadow="never">
          <div class="flex-column-between height83">
            <el-form ref="form"
                     :model="form"
                     :rules="rules"
                     label-width="100px">
              <el-form-item label="套餐标题:"
                            prop="name">
                <el-input clearable
                          :maxlength="100"
                          v-model="form.name"
                          placeholder="请输入分类名称">
                </el-input>
              </el-form-item>

              <el-form-item label="套餐卡副标题:"
                            prop="desc">
                <span slot="label">
                  副标题

                </span>
                <el-input clearable
                          v-model="form.desc"
                          placeholder="请输入套餐卡副标题" />
              </el-form-item>
              <el-form-item label="背景样式:"
                            prop="style_id">
                <span slot="label">
                  背景样式

                </span>
                <el-radio-group v-model="form.style_id"
                                @input="changeStyle">
                  <el-radio :label="1">样式一</el-radio>
                  <el-radio :label="2">样式二</el-radio>
                  <el-radio :label="3">样式三</el-radio>
                  <el-radio :label="4">自定义</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="背景样式:"
                            prop="style">
                <img v-if="!isCustom"
                     :src="backgroundStyle"
                     alt=""
                     class="backgroundImg">

                <el-upload v-else
                           action="#"
                           :on-exceed="exceedFn"
                           list-type="picture-card"
                           :file-list="fileListStyle"
                           :limit="1"
                           :on-change="
                    (files, fileListStyle) => handleFileChange(files, fileListStyle,'backgroundStyle')
                  "
                           :auto-upload="false">
                  <i slot="default"
                     class="el-icon-plus"></i>
                  <div slot="file"
                       slot-scope="{ file }">
                    <img class="el-upload-list__item-thumbnail"
                         :src="file.url"
                         alt="" />
                    <span class="el-upload-list__item-actions">
                      <!-- <span class="el-upload-list__item-preview"
                            @click="handlePictureCardPreview()">
                        <i class="el-icon-zoom-in"></i>
                      </span> -->
                      <span class="el-upload-list__item-delete"
                            @click="handleDownload(file)">
                        <i class="el-icon-download"></i>
                      </span>
                      <span class="el-upload-list__item-delete"
                            @click="handleRemove(file)">
                        <i class="el-icon-delete"></i>
                      </span>
                    </span>
                  </div>
                </el-upload>

              </el-form-item>

              <!-- 提交图片 -->
              <el-form-item label="上传Logo:"
                            prop="logo">
                <el-upload action="#"
                           :on-exceed="exceedFn"
                           list-type="picture-card"
                           :file-list="fileList"
                           :limit="1"
                           :on-change="
                    (files, fileList) => handleFileChange(files, fileList,'logo')
                  "
                           :auto-upload="false">
                  <i slot="default"
                     class="el-icon-plus"></i>
                  <div slot="file"
                       slot-scope="{ file }">
                    <img class="el-upload-list__item-thumbnail"
                         :src="file.url"
                         alt="" />
                    <span class="el-upload-list__item-actions">
                      <span class="el-upload-list__item-preview"
                            @click="handlePictureCardPreview()">
                        <i class="el-icon-zoom-in"></i>
                      </span>
                      <span class="el-upload-list__item-delete"
                            @click="handleDownload(file)">
                        <i class="el-icon-download"></i>
                      </span>
                      <span class="el-upload-list__item-delete"
                            @click="handleRemove2(file)">
                        <i class="el-icon-delete"></i>
                      </span>
                    </span>
                  </div>
                </el-upload>
              </el-form-item>
              <!-- 价格 -->

              <el-form-item label="价格:"
                            prop="price">
                <span slot="label">
                  价格

                </span>
                <el-input clearable
                          min="0"
                          type="number"
                          v-model="form.price"
                          placeholder="请输入价格" />
              </el-form-item>
              <!-- 次数 -->
              <el-form-item label="次数:"
                            prop="number">
                <span slot="label">
                  次数

                </span>
                <el-input clearable
                          min="0"
                          type="number"
                          v-model="form.number"
                          placeholder="请输入次数" />
              </el-form-item>
              <el-form-item label="充值说明:"
                            prop="remark">

                <tinymce-editor v-model="form.remark"
                                :init="editorConfig" />
              </el-form-item>
            </el-form>
            <div class="drawer__footer">
              <el-button round
                         type="plain"
                         @click="handleClose"
                         size="medium">返回</el-button>
              <el-button type="primary"
                         round
                         :loading="loading"
                         size="medium"
                         @click="save">确定</el-button>
            </div>
          </div>
        </el-card>
      </div>
    </el-drawer>
    <!-- 图片预览 -->
    <el-image-viewer v-if="viewerVisible"
                     style="z-index: 9999"
                     :on-close="closeViewer"
                     :url-list="imgViewArr" />
  </div>
</template>

<script>
import TinymceEditor from '@/components/TinymceEditor/index.vue';
import ElImageViewer from 'element-ui/packages/image/src/image-viewer';
// import { getToken } from '@/utils/token-util';
// import {
//   userOssSignature,
//   qnyOssSignature
// } from '@/api/creatCenter/material';
// import { storageConfigDetail } from '@/api/storageInfo/index';

// import axios from 'axios';
// import {
//   siteCategoriesInsert,
//   siteCategoriesList,
//   siteCategoriesModify,
//   siteCategoriesDetail
// } from '@/api/serviceManagement/categoriesList';
import { editPackage, addPackage } from '@/api/package/index'
import { upload } from '@/api/saveImg/index'

export default {
  name: 'pictureEdit',
  components: { ElImageViewer, TinymceEditor },
  props: {
    drawerEditBoolen: {
      type: Boolean,
      default: false
    },
    // 修改回显的数据
    data: Object
  },
  data () {
    const categoryImage = (rule, value, callback) => {
      console.log(this.form.logo);
      if (!this.form.logo) {
        callback(new Error('请上传图片'));
      } else {
        callback();
      }
    };
    const categoryStyle = (rule, value, callback) => {
      console.log(this.form.style);
      if (!this.form.style) {
        callback(new Error('请上传图片'));
      } else {
        callback();
      }
    };
    const DEFAULT_FORM = {
      // 套餐标题
      name: '',
      // 套餐副标题
      desc: '',
      // 背景样式
      style: '',
      // 价格
      price: "",
      // 次数
      number: '',
      // 描述说明
      remark: '',
      // LOGO
      logo: '',
      // 样式选择
      style_id: 1


    };
    return {

      imageUrlStyle: '',
      fileListStyle: [],
      storageMode: '',
      options: [],
      imageUrl: '',
      imgViewArr: [],
      viewerVisible: false,
      // 表单数据
      form: { ...DEFAULT_FORM },
      dialogImageUrl: '',
      fileList: [],
      dialogVisible: false,

      // 表单验证规则
      rules: {
        name: [
          {
            required: true,
            message: '请输入套餐标题',
            trigger: 'blur'
          }
        ],
        desc: [
          {
            required: true,
            message: '请输入套餐副标题',
            trigger: 'blur'
          }
        ],
        price: [
          {
            required: true,
            message: '请输入价格',
            trigger: 'blur'
          }
        ],
        remark: [
          {
            required: true,
            message: '请输入充值说明',
            trigger: 'blur'
          }
        ],
        number: [
          {
            required: true,
            message: '请输入次数',
            trigger: 'blur'
          }
        ],
        // 站点 图片上传
        logo: [
          { required: true, validator: categoryImage, trigger: 'change' }
        ],
        style: [
          { required: true, validator: categoryStyle, trigger: 'change' }
        ]
      },
      editorConfig: {
        height: 525,
        relative_urls: false,
        convert_urls: false,


        images_upload_handler: async (blobInfo, success,) => {



          //  ==================================

          const files = blobInfo.blob();
          // 使用 axios 上传，实际开发这段建议写在 api 中再调用 api
          const param = new FormData();

          param.append('file', files, files.name);


          const res = await upload(param);
          console.log(res.data.url);

          success(res.data.url)



          // });
        }
      },
      // 提交状态
      loading: false,
      // 是否是修改
      isUpdate: false,
      showChoose: false,
      isCustom: false,
      backgroundStyleArr: [
        // '../../static/套餐卡背景/矩形 1590.png',
        // '../../static/套餐卡背景/矩形 1591.png',
        // '../../static/套餐卡背景/组合 907.png'
        'https://n8.weijuyunke.com/2024-05-28/1139c202405280939213122.png',
        'https://n8.weijuyunke.com/2024-05-28/e749e202405280940051410.png',
        'https://n8.weijuyunke.com/2024-05-28/87cb820240528094021945.png'
      ],
      backgroundStyle: ''
    };
  },
  activated () {

  },
  methods: {
    changeStyle (e) {
      console.log(e)
      //  样式类型
      this.form.style_id = e
      if (e == 4) {
        this.isCustom = true
        if (!this.isUpdate) {
          this.fileListStyle = [];
          this.imageUrlStyle = '';
        }

      } else {
        this.isCustom = false
      }
      if (!(e == 4)) {
        this.backgroundStyle = this.backgroundStyleArr[e - 1]
        this.form.style = this.backgroundStyleArr[e - 1]
        console.log(this.backgroundStyle)
      }
    },
    // 获取存储配置
    // async storageConfig () {
    //   const res = await storageConfigDetail();

    //   // console.log(res.storageMode);

    //   this.storageMode = res?.storageMode;
    // },
    // 关闭查看器
    closeViewer () {
      this.viewerVisible = false;
    },
    // 下载图片
    handleDownload (file) {
      window.open(file.url);
    },

    handleRemove () {
      this.fileListStyle = [];
      this.imageUrlStyle = '';
    },
    // 删除图片
    handleRemove2 () {
      this.fileList = [];
      this.imageUrl = '';
      this.form.logo = this.imageUrl
    },
    //  图片上传个数超过限制
    exceedFn () {
      this.$message({
        message: '图片上传已达到上限,请删除后再上传',
        type: 'warning'
      });
    },
    // 关闭抽屉
    handleClose () {
      console.log('查看详情');
      this.$emit('update:drawerEditBoolen', false);
    },
    async handleFileChange (file, fileList, name) {
      this.loading = true;
      console.log(this.storageMode);
      let files = file.raw;

      let param = new FormData();
      param.append('file', files, files.name);
      const res = await upload(param)
      console.log(res)
      if (res.code == 0) {
        if (name == 'backgroundStyle') {
          this.form.style = res.data.url
          this.loading = false;
        } else {
          this.form.logo = res.data.url
          console.log(this.form.logo)
          this.loading = false;
          // res.data.url

        }
      }
      // if(name=='backgroundStyle'){
      //    this.form.style=
      // }

      //   if (this.storageMode == 2) {
      //     this.aliFn(file, fileList);
      //   } else if (this.storageMode == 3) {
      //     this.qnyFn(file, fileList);
      //   }
    },
    // 阿里云
    // async aliFn (file, fileList) {
    //   this.loading = true;
    //   const res = await userOssSignature();
    //   let files = file.raw;
    //   let filename = file.name;
    //   let markIndex = filename.lastIndexOf('.');
    //   let suffix = filename.substring(markIndex);
    //   let date = new Date().getTime();
    //   // 构建请求参数
    //   let param = new FormData();
    //   param.append('key', date + suffix);
    //   param.append('policy', res.policy);
    //   param.append('OSSAccessKeyId', res.accessId);
    //   param.append('success_action_status', '200');
    //   // param.append("callback",  this.data.callback)     //回调（not)
    //   param.append('signature', res.signature);
    //   param.append('file', files, files.name);
    //   param.append('success_action_status', '200');
    //   let config = {
    //     headers: {
    //       'Access-Control-Allow-Origin': '*',
    //       'x-oss-callback-Authorization': getToken()
    //     }
    //   };
    //   console.log('suffix', suffix);

    //   let result = await axios.post(res.host, param, config);
    //   let url = res.host + '/' + date + suffix;
    //   console.log(url);
    //   this.form.categoryImages = url;
    //   this.imageUrl = url;
    //   this.loading = false;
    // },
    // async qnyFn (file, fileList) {
    //   this.loading = true;
    //   console.log(file, fileList);

    //   let files = file.raw;
    //   console.log(files);
    //   //   // 构建请求参数
    //   let param = new FormData();

    //   param.append('file', files, files.name);
    //   param.append('getsize', files.size);
    //   param.append('getContentType', files.type);
    //   param.append('getoriginalfilename', files.name);
    //   param.append('getName', files.name);

    //   const res = await qnyOssSignature(param);
    //   console.log(res.url);
    //   this.form.categoryImages = res.url;
    //   this.imageUrl = res.url;
    //   console.log('上传图片成功=======', res);
    //   this.loading = false;
    // },
    // 点击按钮预览图片
    handlePictureCardPreview () {
      const imgStr = this.imageUrl;
      console.log(imgStr);
      if (imgStr.length) {
        if (imgStr.includes(',')) {
          console.log('字符串中包含逗号');
          // 包含的进行slice(',') 分割

          this.imgViewArr = imgStr.split(',').map((item) => item.trim());
        } else {
          console.log('字符串中不包含逗号');
          this.imgViewArr = imgStr.split();
        }

        this.viewerVisible = true;
      } else {
        this.$message({
          message: '没有上传图片无法进行预览',
          type: 'warning'
        });
      }
    },
    /* 保存编辑 */
    save () {
      this.$refs['form'].validate((valid) => {
        if (!valid) {
          return false;
        }
        // if (this.isUpdate) {
        //   this.form.logo = this.imageUrl;
        //   this.form.style = this.imageUrlStyle
        // }
        const data = {
          ...this.form
        };
        console.log(data);
        this.loading = true;

        const saveOrUpdate = this.isUpdate
          ? editPackage
          : addPackage;
        saveOrUpdate(data)
          .then((msg) => {
            console.log(msg);
            this.loading = false;
            this.$message.success(msg.message);

            this.handleClose();
            this.$emit('done');
          })
          .catch((e) => {
            this.loading = false;
            this.$message.error(e.message);
          });
      });
    }
    /* 更新visible */
  },
  watch: {
    drawerEditBoolen (visible) {
      this.$nextTick(() => {
        if (visible) {
          this.isCustom = false
          console.log(this.data);
          if (this.data) {
            this.form.id = '';
            this.$util.assignObject(this.form, {
              ...this.data
            });
            this.backgroundStyle = this.backgroundStyleArr[this.form.style_id - 1]
            if (this.form.logo) {
              this.imageUrl = this.form.logo;
              let markIndex = this.form.logo.lastIndexOf('.');
              let suffix = this.form.logo.substring(markIndex);
              if (!this.fileList.length) {
                this.fileList.push({
                  name: suffix,
                  url: this.form.logo
                });
              } else {
                this.fileList = [
                  {
                    name: suffix,
                    url: this.form.logo
                  }
                ];
              }
            } else {
              this.fileList = [];
            }
            if (this.form.style) {
              if (this.form.style_id == 4) {
                this.isCustom = true
                let markIndex = this.form.style.lastIndexOf('.');
                let suffix = this.form.style.substring(markIndex);
                if (!this.fileListStyle.length) {
                  this.fileListStyle.push({
                    name: suffix,
                    url: this.form.style
                  });
                } else {
                  this.fileListStyle = [
                    {
                      name: suffix,
                      url: this.form.style
                    }
                  ];
                }
              }

              this.imageUrlStyle = this.form.style;

              console.log(this.fileListStyle)
            } else {
              this.fileListStyle = [];
            }
            if (!this.form.style_id) {
              this.form.style_id = 1
            }
            this.isUpdate = true;
          } else {
            this.isUpdate = false;
            this.backgroundStyle = this.backgroundStyleArr[this.form.style_id - 1]
            this.form.style = this.backgroundStyleArr[0]
          }
        } else {
          this.$nextTick(() => {
            this.$refs['form'].resetFields();
            console.log(this.form);
          });
          this.fileList = [];

        }
      });
    }
  }
};
</script>

<style lang="less" scoped>
/deep/.el-upload-list__item {
  transition: none !important;
  -webkit-transition: nonne !important;
}
/deep/.el-upload-list__item-name {
  transition: none !important;
  -webkit-transition: nonne !important;
}
/*隐藏input（type=number)右边的小箭头*/
/deep/.delInput input::-webkit-outer-spin-button,
/deep/.delInput input::-webkit-inner-spin-button {
  -webkit-appearance: none !important;
}
/deep/.delInput input[type='number'] {
  -moz-appearance: textfield;
}
.backgroundImg {
  height: 75px;
}
.foodsDiv div {
  margin-left: 20px;
  margin-top: 10px;
}
.height83 {
  min-height: 83vh;
}
.hLabel {
  margin: 10px 0 20px;
  font-weight: 700;
  &::before {
    content: '';
    display: inline-block;
    vertical-align: top;

    margin-right: 5px;
    height: 23px;
    width: 6px;
    background-color: #1e6ceb;
  }
}
.drawer__footer {
  display: flex;
  justify-content: flex-start;
  margin-left: 15px;
}
</style>
